class Sample():
    def __enter__(self):
        print('enter')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('exit')

    def do_sth(self):
        print('do sth')
with Sample() as sample:
    sample.do_sth()

#contextlib简化上下文管理器
import contextlib
@contextlib.contextmanager
def file_open(filename):
    print('open_file')#相当于写在__enter__里的语句
    yield {}
    print('file_end')#相当于__exit__里的语句

with file_open('抽象基类(abc模块).py') as f:
    print('file_processing')